package com.suneast.suneaststore.modules.store;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.suneast.suneaststore.API;
import com.suneast.suneaststore.app.AccountManager;
import com.suneast.suneaststore.bean.homepage.StoreListBean;
import com.suneast.suneaststore.modules.homepage.event.StoreListResult;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.common.CommonUtil;
import com.suneast.suneaststore.bean.store.StoreCateBean;
import com.suneast.suneaststore.bean.store.StoreGoodsBean;
import com.suneast.suneaststore.bean.store.StoreInfoBean;
import com.suneast.suneaststore.modules.store.event.GotStoreCollectState;
import com.suneast.suneaststore.modules.store.event.GotStoreGoodsList;
import com.suneast.suneaststore.modules.store.event.GotStorePageData;
import com.suneast.suneaststore.modules.store.event.StoreCollectResult;
import com.suneast.suneaststore.modules.store.event.StoreRequestFail;
import com.suneast.suneaststore.util.log.LatteLogger;
import com.suneast.suneaststore.util.net.RestClient;
import com.suneast.suneaststore.util.net.RestClientBuilder;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.WeakHashMap;

public class StoreHandler {
    private final static int[] FILTER_TYPES = new int[]{
            0, //默认
            1, //好评
            2  //销量
    };
    private final static int[] STORE_TYPES = new int[]{
            2, //中心
            3  //店
    };

    private final static int psize = 8; // 一页的条目数

    static void requestStoreList(int typeChoice, int filterChoice, float latitude, float longitude, int page) {
        RestClientBuilder builder = RestClient.builder()
                .url(API.MERCH_LIST)
                .params("page", page)
                .params("psize", psize)
                .params("type", STORE_TYPES[typeChoice])
                .params("sorttype", FILTER_TYPES[filterChoice])
                .success((response) -> {
                    LatteLogger.json(API.MERCH_LIST, response);
                    JSONObject rootJObj = JSONObject.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new StoreListResult(Flag.Result.SUCCEED, typeChoice, filterChoice,
                                JSON.parseObject(rootJObj.getJSONObject("data").toJSONString(), StoreListBean.class)));
                    } else {
                        EventBus.getDefault().post(new StoreListResult(Flag.Result.FAILURE, typeChoice, filterChoice, rootJObj.getString("msg")));
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", "requestStoreList failure");
                    EventBus.getDefault().post(new StoreListResult(Flag.Result.FAILURE, typeChoice, filterChoice, "请求失败"));
                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", "requestStoreList error code = "
                            + code + " msg = " + msg);
                    EventBus.getDefault().post(new StoreListResult(Flag.Result.FAILURE, typeChoice, filterChoice, "code = " + code + " msg = " + msg));
                });
        if (latitude > 0 || longitude > 0) {
            builder.params("lat", latitude)
                    .params("lng", longitude);
        }
        builder.build().post();
    }

    static void requestStorePage(int merchId) {
        RestClient.builder()
                .url(API.MERCH_HOME_PAGE)
                .params("merchid", merchId)
                .success(response -> {
                    LatteLogger.json("test", response);
                    JSONObject dataObj = CommonUtil.parseDataFromRootJSON(response);
                    if (dataObj != null) {
                        StoreInfoBean storeInfoBean = JSON.parseObject(
                                dataObj.getJSONObject("store").toJSONString(),
                                StoreInfoBean.class);
                        List<String> bannerList = JSON.parseArray(
                                dataObj.getJSONArray("banner").toJSONString(), String.class);
                        JSONObject goodsObj = dataObj.getJSONObject("goods");
                        JSONArray goodsList = goodsObj.getJSONArray("list");
                        List<StoreGoodsBean> goodsBeanList =
                                JSON.parseArray(goodsList.toJSONString(), StoreGoodsBean.class);
                        List<StoreCateBean> finishedProductCates =
                                JSON.parseArray(dataObj.getJSONArray("endCates").toJSONString()
                                        , StoreCateBean.class);
                        List<StoreCateBean> materialCates =
                                JSON.parseArray(dataObj.getJSONArray("materialCates").toJSONString()
                                        , StoreCateBean.class);
                        EventBus.getDefault().post(new GotStorePageData(
                                storeInfoBean,
                                bannerList,
                                goodsBeanList,
                                finishedProductCates,
                                materialCates
                        ));
                    } else {
                        LatteLogger.e("error",
                                " requestStorePage succeed but dataObj  illegality ");
                    }
                })
                .error((code, msg) -> {
                    EventBus.getDefault().post(new StoreRequestFail(0));
                    LatteLogger.e("error", " requestStorePage error code = " + code + " msg = " + msg);
                })
                .failure(() -> {
                    EventBus.getDefault().post(new StoreRequestFail(0));
                    LatteLogger.e("error", " requestStorePage failure ");
                })
                .build()
                .post();
    }

    static void collectStoreOrNot(int merchId) {
        RestClient.builder()
                .url(API.COLLECT_STORE)
                .params("token", AccountManager.getToken())
                .params("merchid", merchId)
                .success(response -> {
                    LatteLogger.json("test", response);
                    JSONObject dataObj = CommonUtil.parseDataFromRootJSON(response);
                    if (dataObj != null) {
                        EventBus.getDefault().post(new StoreCollectResult(Flag.Result.SUCCEED, dataObj.getIntValue("type")));
                    } else {
                        EventBus.getDefault().post(new StoreCollectResult(Flag.Result.FAILURE, 1));
                    }
                })
                .error((code, msg) -> {
                    EventBus.getDefault().post(new StoreCollectResult(Flag.Result.FAILURE, 1));
                    LatteLogger.e("error", " collectStoreOrNot error code = " + code + " msg = " + msg);
                })
                .failure(() -> {
                    EventBus.getDefault().post(new StoreCollectResult(Flag.Result.FAILURE, 1));
                    LatteLogger.e("error", " collectStoreOrNot failure ");
                })
                .build()
                .post();
    }

    static void requestStoreCollectState(int merchId) {
        RestClient.builder()
                .url(API.GET_STORE_COLLECT_STATE)
                .params("token", AccountManager.getToken())
                .params("merchid", merchId)
                .success(response -> {
                    LatteLogger.json("test", response);
                    JSONObject dataObj = CommonUtil.parseDataFromRootJSON(response);
                    if (dataObj != null) {
                        EventBus.getDefault().post(new GotStoreCollectState(Flag.Result.SUCCEED, dataObj.getIntValue("status")));
                    } else {
                        EventBus.getDefault().post(new GotStoreCollectState(Flag.Result.FAILURE, 1));
                    }
                })
                .error((code, msg) -> {
                    EventBus.getDefault().post(new GotStoreCollectState(Flag.Result.FAILURE, 1));
                    LatteLogger.e("error", " requestStoreCollectState error code = " + code + " msg = " + msg);
                })
                .failure(() -> {
                    EventBus.getDefault().post(new GotStoreCollectState(Flag.Result.FAILURE, 1));
                    LatteLogger.e("error", " requestStoreCollectState failure ");
                })
                .build()
                .post();

    }

    static void requestGoodsList(WeakHashMap<String, Object> params) {
        RestClient.builder()
                .url(API.GET_STORE_GOODS)
                .params(params)
                .success(response -> {
                    LatteLogger.json("test", response);
                    JSONObject dataObj = CommonUtil.parseDataFromRootJSON(response);
                    if (dataObj != null) {
                        List<StoreGoodsBean> list = JSON.parseArray(
                                dataObj.getJSONArray("list").toJSONString(),
                                StoreGoodsBean.class);
                        double total = dataObj.getDoubleValue("total");
                        int psize = dataObj.getIntValue("psize");
                        EventBus.getDefault().post(new GotStoreGoodsList(list, (int)total, psize));
                    }
                })
                .error((code, msg) -> {
                    EventBus.getDefault().post(new StoreRequestFail(1));
                    LatteLogger.e("error", " requestGoodsList error code = " + code + " msg = " + msg);
                })
                .failure(() -> {
                    EventBus.getDefault().post(new StoreRequestFail(1));
                    LatteLogger.e("error", " requestGoodsList failure ");
                })
                .build()
                .post();
    }
}
